package com.ruoyi.auth.controller;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import com.ruoyi.auth.form.LoginBody;
import com.ruoyi.auth.form.RegisterBody;
import com.ruoyi.auth.service.SysLoginService;
import com.ruoyi.auth.util.HttpUtils;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.JwtUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.security.auth.AuthUtil;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.model.LoginUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * token 控制
 *
 * @author ruoyi
 */
@RestController
public class TokenController
{
    @Autowired
    private TokenService tokenService;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    private SysLoginService sysLoginService;

    @PostMapping("login")
    public R<?> login(@RequestBody LoginBody form)
    {
        // 用户登录
        LoginUser userInfo = sysLoginService.login(form.getUsername(), form.getPassword());
        // 获取登录token
        return R.ok(tokenService.createToken(userInfo));
    }

    @DeleteMapping("logout")
    public R<?> logout(HttpServletRequest request)
    {
        String token = SecurityUtils.getToken(request);
        if (StringUtils.isNotEmpty(token))
        {
            String username = JwtUtils.getUserName(token);
            // 删除用户缓存记录
            AuthUtil.logoutByToken(token);
            // 记录用户退出日志
            sysLoginService.logout(username);
        }
        return R.ok();
    }

    @PostMapping("refresh")
    public R<?> refresh(HttpServletRequest request)
    {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser))
        {
            // 刷新令牌有效期
            tokenService.refreshToken(loginUser);
            return R.ok();
        }
        return R.ok();
    }

    @PostMapping("register")
    public R<?> register(@RequestBody RegisterBody registerBody)
    {
        // 用户注册
        sysLoginService.register(registerBody.getUsername(), registerBody.getPassword(),registerBody.getCode());
        return R.ok();
    }
    @PostMapping("sendCode/{username}")
    public R<?> sendCode(@PathVariable String username){
//        String code = RandomUtil.randomNumbers(4);
//        redisTemplate.opsForValue().set("Mobile"+username, code, 3, TimeUnit.MINUTES);
//        String host = "https://dxyzm.market.alicloudapi.com";
//        String path = "/chuangxin/dxjk";
//        String method = "POST";
//        String appcode = "4ea87b9c66394ea3bd37fd72320fe3ed";//开通服务后 买家中心-查看AppCode
//        Map<String, String> headers = new HashMap<String, String>();
//        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
//        headers.put("Authorization", "APPCODE " + appcode);
//        Map<String, String> querys = new HashMap<String, String>();
//        querys.put("content", "【创信】你的验证码是："+ code +"，3分钟内有效！");
//        querys.put("mobile", username);
//        Map<String, String> bodys = new HashMap<String, String>();
//        try {
//            /**
//             * 重要提示如下:
//             * HttpUtils请从
//             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
//             * 下载
//             *
//             * 相应的依赖请参照
//             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
//             */
////            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
////            System.out.println(response.toString());
//            //获取response的body
////            System.out.println(EntityUtils.toString(response.getEntity()));
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//
//        // 验证码发送成功
//        return R.ok(code,"验证码发送成功");
//    }
        /*使用阿里sms短信服务*/
        if (!StringUtils.isBlank(username)){
            String code = RandomUtil.randomNumbers(4);
            String url = "http://gyytz.market.alicloudapi.com/sms/smsSend";
            String appcode = "4ea87b9c66394ea3bd37fd72320fe3ed";
            /*最后在header中的格式(中间是英文空格)为Authorization:APPCODE
            // 83359fd73fe94948385f570e3c139105//  map.put("Authorization", "APPCODE " + appcode);*/
            Map<String, Object> map = new HashMap<>();
            map.put("mobile",username);
            /*/smsSignId（短信前缀）和templateId（短信模板），可登录国阳云控制台自助申请。
            // 参考文档：http://help.guoyangyun.com/Problem/Qm.html*/
            map.put("param", "**code**:"+code+",**minute**:2");
            map.put("smsSignId", "2e65b1bb3d054466b82f0c9d125465e2");
            map.put("templateId", "908e94ccf08b4476ba6c876d13f084ad");
            String body= HttpRequest.post(url)
                    .header("Authorization","APPCODE "+appcode)
                    .form(map)
                    .execute().body();

            redisTemplate.opsForValue().set("Mobile"+username, code, 30, TimeUnit.MINUTES);
            if (body.contains("成功")){
                return R.ok(code,"验证码发送成功");
            }else {
                return R.fail("验证码发送失败");
            }
        }else {
            return R.fail("手机号不能为空");
        }
    }
}
